package com.ttctracker.search;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;

import javax.xml.parsers.ParserConfigurationException;

import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import com.ttctracker.R;
import com.ttctracker.classes.Direction;
import com.ttctracker.classes.Route;
import com.ttctracker.classes.StopItem;
import com.ttctracker.map.Map;
import com.ttctracker.util.MyApp;
import com.ttctracker.util.RouteStopsParseHandler;
import com.ttctracker.util.SqlAdapter;
import com.ttctracker.xmlparser.SAXParserHelper;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.ListView;
import android.widget.Spinner;

public class Search extends Activity implements OnItemClickListener {
	private AutoCompleteTextView _txt_route;
	private HashMap<String, String> route_tags;
	private MyApp myApp;
	private Spinner _spinner_direction;
	private ListView _list_stop;
	private String[] route_tags_keys, route_tags_titles;
	private Route searchRoute;
	private ArrayList<StopItem> stopItems;
	private StopArrayAdapter stopArrayAdapter;
	private String selectedRoute, selectedDirection;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.view_search);
		myApp = (MyApp) getApplicationContext();
		setup_layout();
	}

	private void setup_layout() {
		selectedRoute = "";
		selectedDirection = "";

		_txt_route = (AutoCompleteTextView) findViewById(R.id.txt_search_route);
		_spinner_direction = (Spinner) findViewById(R.id.spinner_direction);
		_list_stop = (ListView) findViewById(R.id.view_search_stop_list);

		_spinner_direction.setEnabled(false);
		// _spinner_stop.setEnabled(false);

		// route_tags = myApp.getRouteTags();

		route_tags_keys = myApp.getRoute_tags_keys();
		route_tags_titles = myApp.getRoute_tags_titles();

		_txt_route.setAdapter(myApp.getRouteAdapter());

		_txt_route.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				MyApp.hideKeyBoard(Search.this, _txt_route);
				selectedRoute = route_tags_keys[Arrays.binarySearch(
						route_tags_titles, arg0.getItemAtPosition(arg2))];
				new SearchRouteTask().execute(selectedRoute);
			}
		});
		
		
		
		_txt_route.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				
				((AutoCompleteTextView)v).selectAll();
				
			}
		});
		//_txt_route.requestFocus();
		
		stopItems = new ArrayList<StopItem>();
		stopArrayAdapter = new StopArrayAdapter(Search.this,
				android.R.layout.simple_spinner_dropdown_item, stopItems);
		_list_stop.setAdapter(stopArrayAdapter);
		_list_stop.setEmptyView(findViewById(R.id.view_search_empty));
		_list_stop.setOnItemClickListener(this);
	}

	private class SearchRouteTask extends AsyncTask<String, Void, Route> {

		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
			progressDialog = new ProgressDialog(Search.this);
			progressDialog.setMessage("Loading Stop information...");
			progressDialog.show();
		}

		@Override
		protected Route doInBackground(String... arg0) {
			try {
				SqlAdapter dbAdapter = new SqlAdapter(Search.this);
				dbAdapter.openDB();
				if (dbAdapter.isOpen()) {
					Route result = dbAdapter.selectRoute(arg0[0],false);
					if (result != null) {
						dbAdapter.close();
						return result;
					}
					dbAdapter.close();
				}

			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

		@Override
		protected void onPostExecute(Route result) {
			progressDialog.dismiss();
			if (result != null) {
				searchRoute = result;

				DirectionArrayAdapter spinnerAdapter = new DirectionArrayAdapter(
						Search.this,
						android.R.layout.simple_spinner_dropdown_item,
						result.get_directions());

				_spinner_direction.setAdapter(spinnerAdapter);
				_spinner_direction.setEnabled(true);
				_spinner_direction
						.setOnItemSelectedListener(new OnItemSelectedListener() {

							@Override
							public void onItemSelected(AdapterView<?> arg0,
									View arg1, int arg2, long arg3) {
								Direction tempDirection = (Direction) arg0
										.getItemAtPosition(arg2);
								selectedDirection = tempDirection.get_title();

								ArrayList<String> stops = tempDirection
										.get_stops();
								HashMap<String, StopItem> route_stops = searchRoute
										.get_stopItems();

								stopItems.clear();
								for (String stop : stops) {
									stopItems.add(route_stops.get(stop));
								}
								stopArrayAdapter.notifyDataSetChanged();
							}

							@Override
							public void onNothingSelected(AdapterView<?> arg0) {
								// TODO Auto-generated method stub

							}
						});
			}

		}
	}

	@Override
	public void onItemClick(AdapterView<?> adapterView, View view,
			int position, long arg3) {
		StopItem selectedStopItem = (StopItem) adapterView
				.getItemAtPosition(position);
		if (selectedStopItem != null) {
			String url = "http://webservices.nextbus.com/service/publicXMLFeed?command=predictions&a=ttc&r="
					+ selectedRoute + "&s=" + selectedStopItem.get_tag();
			new SearchPredictionTask(this).execute(url);
		}

	}
	
}
